from flask import Flask, render_template_string
import boto3
import os
import threading
import json
from datetime import datetime

app = Flask(__name__)

s3_events = []
events_lock = threading.Lock()

HTML_TEMPLATE = '''
<!DOCTYPE html>
<html>
<head>
    <title>S3 Events Monitor</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; }
        .event { border: 1px solid #ddd; padding: 10px; margin: 10px 0; border-radius: 5px; }
        .new { background-color: #e8f5e8; border-left: 4px solid #4CAF50; }
        .header { background-color: #f5f5f5; padding: 20px; border-radius: 5px; }
    </style>
</head>
<body>
    <div class="header">
        <h1>📊 S3 Bucket Events Monitor</h1>
        <p><strong>Bucket:</strong> {{ bucket_name }}</p>
        <p><strong>Total Events:</strong> {{ events|length }}</p>
    </div>
    
    <h2>Recent S3 Events:</h2>
    <div id="events">
        {% for event in events %}
        <div class="event {% if loop.index0 == 0 %}new{% endif %}">
            <strong>🕒 Time:</strong> {{ event.time }}<br>
            <strong>📝 Event:</strong> {{ event.event_type }}<br>
            <strong>🔑 Key:</strong> {{ event.key }}<br>
            <strong>📦 Size:</strong> {{ event.size }} bytes
        </div>
        {% else %}
        <p>No events received yet. Upload a file to the S3 bucket to see events here.</p>
        {% endfor %}
    </div>
    
    <script>
        // 每5秒自动刷新页面
        setTimeout(() => location.reload(), 5000);
    </script>
</body>
</html>
'''

def poll_sqs_events():
    """在后台线程中轮询SQS队列获取S3事件"""
    sqs_client = boto3.client('sqs')
    queue_url = os.environ.get('SQS_QUEUE_URL')
    
    while True:
        try:
            if not queue_url:
                print("SQS_QUEUE_URL environment variable not set")
                continue
                
            response = sqs_client.receive_message(
                QueueUrl=queue_url,
                MaxNumberOfMessages=10,
                WaitTimeSeconds=20
            )
            
            if 'Messages' in response:
                for message in response['Messages']:
                    try:
                        # EventBridge发送的消息格式
                        body = json.loads(message['Body'])
                        print(f"Received message: {json.dumps(body, indent=2)}")
                        
                        # 处理EventBridge格式的事件
                        if 'detail' in body:
                            detail = body['detail']
                            event_time = body.get('time', datetime.utcnow().isoformat())
                            event_name = detail.get('eventName', 'Unknown')
                            
                            # 从请求参数中提取对象信息
                            request_params = detail.get('requestParameters', {})
                            key = request_params.get('key', 'Unknown')
                            
                            with events_lock:
                                s3_events.insert(0, {
                                    'time': event_time,
                                    'event_type': event_name,
                                    'key': key,
                                    'size': 'N/A'  # EventBridge事件中可能不包含大小信息
                                })
                                # 只保留最近20个事件
                                if len(s3_events) > 20:
                                    s3_events.pop()
                    
                    except Exception as e:
                        print(f"Error processing message: {e}")
                    
                    finally:
                        # 删除已处理的消息
                        sqs_client.delete_message(
                            QueueUrl=queue_url,
                            ReceiptHandle=message['ReceiptHandle']
                        )
                        
        except Exception as e:
            print(f"Error polling SQS: {e}")

@app.route('/')
def index():
    with events_lock:
        events_copy = s3_events.copy()
    
    return render_template_string(HTML_TEMPLATE,
                         events=events_copy,
                         bucket_name=os.environ.get('S3_BUCKET_NAME', 'Unknown'))

if __name__ == '__main__':
    # 启动后台线程轮询SQS
    if os.environ.get('SQS_QUEUE_URL'):
        sqs_thread = threading.Thread(target=poll_sqs_events, daemon=True)
        sqs_thread.start()
        print("SQS polling thread started")
    else:
        print("SQS_QUEUE_URL not set, SQS polling disabled")
    
    app.run(host='0.0.0.0', port=80)